package com.xflib.framework.util;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class EncryptionAesUtil {
    private static String ALGORITHM_MODE="AES/CBC/PKCS5Padding";
    private static String ALGORITHM = "AES";
    private static String VECTOR_KEY = "012345#789abcdef";
    private static String SLAT_KEY = "012345@789abcdef";

    public static EncryptionAesUtil create(){
        EncryptionAesUtil encryptionAesUtil =new EncryptionAesUtil();
        return encryptionAesUtil;
    }
    public static EncryptionAesUtil create(String slatKey){
        EncryptionAesUtil encryptionAesUtil =new EncryptionAesUtil();
        encryptionAesUtil.SLAT_KEY=slatKey;
        return encryptionAesUtil;
    }
    /**
     * content: 加密内容
     * slatKey: 加密的盐，16位字符串
     * vectorKey: 加密的向量，16位字符串
     */
    public String encrypt(String content, String slatKey, String vectorKey) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM_MODE);
        SecretKey secretKey = new SecretKeySpec(slatKey.getBytes(), ALGORITHM);
        IvParameterSpec iv = new IvParameterSpec(vectorKey.getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
        byte[] encrypted = cipher.doFinal(content.getBytes());
        return Base64.getEncoder().encodeToString(encrypted);
    }
    public String encrypt(String base64Content) throws Exception {
        return encrypt(base64Content,SLAT_KEY,VECTOR_KEY);
    }

    /**
     * content: 解密内容(base64编码格式)
     * slatKey: 加密时使用的盐，16位字符串
     * vectorKey: 加密时使用的向量，16位字符串
     */
    public String decrypt(String base64Content, String slatKey, String vectorKey) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKey secretKey = new SecretKeySpec(slatKey.getBytes(), ALGORITHM);
        IvParameterSpec iv = new IvParameterSpec(vectorKey.getBytes());
        cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
        byte[] content = Base64.getDecoder().decode(base64Content);
        byte[] encrypted = cipher.doFinal(content);
        return new String(encrypted);
    }
    public String decrypt(String base64Content) throws Exception {
        return decrypt(base64Content,SLAT_KEY,VECTOR_KEY);
    }


    public static void main( String[] args ) throws Exception {
        EncryptionAesUtil encryptionAesUtil = EncryptionAesUtil.create("012345@#89abcdef");
        String aaa= encryptionAesUtil.encrypt("asefasd2134#@",SLAT_KEY,VECTOR_KEY);
        String bbb= encryptionAesUtil.decrypt(aaa,SLAT_KEY,VECTOR_KEY);
        System.out.println(bbb);
    }

}
